package com.proxy.autoclick.ui.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.inject.Inject;
import javax.inject.Named;

import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;

import com.proxy.autoclick.checker.controller.ProxyCheckingController;
import com.proxy.autoclick.clicker.controller.ClickerController;
import com.proxy.autoclick.ui.layout.MainFrame;

@Named
public class UIController {
	
//	private static final Logger LOGGER = Logger.getLogger(UIController.class);
	
	private Future<Boolean> result1 = null;
	
	private Future<Boolean> result2 = null;
	
	@Autowired
	private ProxyCheckingController proxyCheckingController;
	
	@Autowired
	private ClickerController clickerController;
	
	@Inject
	private MainFrame mainframe;
	
	private ExecutorService executorService = null;
	
	public void process()
	{
		try 
		{
			checkConfig();
			executorService = Executors.newFixedThreadPool(2);
			executeProxyChecking();
			executeTargetClicking();
		} catch (Exception e) {
			e.printStackTrace();
			mainframe.setTextAreaText(e.getMessage());
		}
	}
	
	private void checkConfig() throws FileNotFoundException
	{
		if(StringUtil.isBlank(mainframe.getSelectFilePath()))
    		throw new RuntimeException("Please select a source file.");
		File file = new File(mainframe.getSelectFilePath());
		if(!file.isDirectory() && !file.exists())
			throw new FileNotFoundException(String.format("The file %s is not exits.", 
					mainframe.getSelectFilePath()));
	}
	
	private void executeProxyChecking()
	{
		Callable<Boolean> task1 = new Callable<Boolean>() {
			public Boolean call() {
				
				try {
					proxyCheckingController.startCheck();
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				return Boolean.TRUE;
			}
		};
		result1 = executorService.submit(task1);
	}
	
	private void executeTargetClicking()
	{
		Callable<Boolean> task2 = new Callable<Boolean>() {
			public Boolean call() {
				
				try {
					clickerController.startCheckAndClick();
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				return Boolean.TRUE;
			}
		};
		result2 = executorService.submit(task2);
	}

	public boolean isThreadRunning() {
		return (this.result1 != null && this.result2 != null) && 
				!(this.result1.isDone() && this.result2.isDone());
	}

}
